#pragma strict
#pragma downcast
import System;
import System.Text;
//////////////////////////////////////////////////////
///Transform助手
//////////////////////////////////////////////////////
class TransformHelper{
	private static var pathSlash:String = "/";
	/** 插值因子 */
	static var t:float = 0;
	
	/**递归查找 名为name的子Transform*/
	static function RecursionFind(t:Transform,name:String):Transform{
		if(t){
			if(t.name == name){
				return t;
			}else{
				for(var c:Transform in t){
					var r:Transform = RecursionFind(c,name);
					if(r != null){
						return r;
					}
				}
			}
		}else{
			Debug.LogWarning("Transform is null!");
		}
		return null;
	}
	

	/** 递归改变 layer */
	static function SetLayerRecursively(t:Transform,layerName:String){
		var layer:int = LayerMask.NameToLayer(layerName);
		if(layer >=0 && layer < 32)
			SetLayerRecursively(t,layer);
		else
			Debug.LogError("layer出界:"+layer);
	}
	
	static function SetLayerRecursively(t:Transform,layer:int){
		if(t){
			t.gameObject.layer = layer;
			for(var tran:Transform in t){
				tran.gameObject.layer = layer;
				SetLayerRecursively(tran,layer);
			}
		}
	}
	
	static function RandomColor(t:Transform){
		var renderer:SkinnedMeshRenderer = t.GetComponentInChildren(SkinnedMeshRenderer);
			renderer.material.color = Vector4(UnityEngine.Random.Range(0,1)
			,UnityEngine.Random.Range(0,1)
			,UnityEngine.Random.Range(0,1)
			,UnityEngine.Random.Range(0,1));
	}
	/** 移除全部子 */
	static function DestroyAll(root:Transform):int{
		var count:int = 0;
		if(root != null){
			for(var i:int = root.childCount-1 ; i >= 0 ; i--){
				GameObject.DestroyImmediate(root.GetChild(i).gameObject);
				count++;
			}
		}
		return count;
	}
	/** 插值式,过渡旋转. */
	static function LerpRotY(oldAngle:float,newAngle:float){
		if(t >= 1)
			t = 0;
		else
			t += 0.1;
		return Mathf.LerpAngle(oldAngle,newAngle,t);
	}
	
	static function IsOppositeDir(v1:Vector3,v2:Vector3){
		return Vector3.Dot(v1.normalized,v2.normalized) < 0;
	}
	
	/** 打印Transform的完整路径. */
	static function GetAbsolutePath(root:Transform):String{
		var sb:StringBuilder = new StringBuilder();
		var p:Transform = root.parent;
		sb.Append(root.gameObject.name);
		while(p != null){
			sb.Append("/").Append(p.gameObject.name);
			p = p.parent;
		}
		return sb.ToString();
	}
	/**
		获取ransform的完整路径.
		Transform : 从此transform开始查找
		rootName: transform的节点名字为rootName时,结束
	*/
	static function GetAbsolutionPath(t:Transform,rootName:String):String{
		var sb:StringBuilder = new StringBuilder();
		var p:Transform = t;
		while(p){
			sb.Insert(0,p.name);
			if(p.name != rootName){
				sb.Insert(0,pathSlash);
			}else{
				break;
			}
			p = p.parent;
		}
		return sb.ToString();
	}
	
	static function GetComponent(go:GameObject,compType:Type):Component{
		var c:Component = go.GetComponent(compType);
		if(! c)
			c = go.AddComponent(compType);
		return c;
	}
}
